<template>
  <div>
    <el-card
      shadow="always"
      :body-style="{ padding: '20px' }"
      :style="{ marginTop: '20px' }"
    >
      <el-form label-width="80px">
        <el-form-item label="SPU名称">
          <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select
            clearable
            filterable
            placeholder="请选择"
            v-model="(spuInfo.tmId as number)"
          >
            <el-option
              v-for="trademark in trademarkList"
              :key="trademark.id"
              :label="trademark.tmName"
              :value="trademark.id!"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="spu描述">
          <el-input
            type="textarea"
            placeholder="请输入"
            v-model="spuInfo.description"
          ></el-input>
        </el-form-item>
        <el-form-item label="Spu图片">
          <el-upload
            v-model:file-list="(saleImageList as any)"
            :action="`${baseUrl}/admin/product/upload`"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            list-type="picture-card"
          >
            <el-icon><ele-Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img
              w-full
              :src="dialogImageUrl"
              alt="Preview Image"
              class="uploadImg"
            />
          </el-dialog>
        </el-form-item>
        <el-form-item label="销售属性">
          <el-select
            placeholder="请选择"
            clearable
            filterable
            v-model="baseSaleValue"
          >
            <el-option
              v-for="baseSale in onUseSaleList"
              :key="baseSale.id"
              :label="baseSale.name"
              :value="`${baseSale.id}:${baseSale.name}`"
            >
            </el-option>
          </el-select>
          <el-button
            type="primary"
            size="default"
            icon="ele-Plus"
            @click="addSalevalue"
            >添加销售属性</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-table :data="saleAttrList" border stripe>
            <el-table-column type="index" width="80" label="序号" />
            <el-table-column label="属性名" width="100" prop="saleAttrName">
            </el-table-column>
            <el-table-column label="属性值名称列表">
              <template v-slot="{ row }">
                <el-tag
                  v-for="(item, index) in row.spuSaleAttrValueList"
                  :key="item.id"
                  type="danger"
                  size="small"
                  effect="dark"
                  :style="{ marginLeft: '20px' }"
                  @close="deleteAttrValue(row, index)"
                  closable
                >
                  {{ item.saleAttrValueName }}</el-tag
                >
                <el-input
                  v-if="row.isEdit"
                  ref="inpEle"
                  size="small"
                  clearable
                  @blur="goLook(row)"
                  @keyup.enter="inpEle.blur()"
                  v-model="row.iptValue"
                ></el-input>

                <el-button
                  v-else
                  type="primary"
                  size="small"
                  icon="ele-Plus"
                  :style="{ float: 'right' }"
                  @click="goEdit(row)"
                  >添加销售属性值</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template v-slot="{ row, $index }">
                <el-popconfirm
                  title="确认要删除吗"
                  @confirm="deleteAttr($index)"
                >
                  <template #reference>
                    <div>
                      <el-tooltip content="删除" placement="top" effect="dark">
                        <el-button
                          type="danger"
                          size="small"
                          icon="ele-Delete"
                        ></el-button>
                      </el-tooltip>
                    </div>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" @click="save"
            >保存</el-button
          >
          <el-button type="default" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import type { spuInfoItemType } from "@/api/spu";
import { storeToRefs } from "pinia";

export default defineComponent({
  name: "AddSpu",
});
</script>

<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from "vue";
import { cloneDeep } from "lodash";
import { ElMessage, type UploadProps } from "element-plus";
import { reqTrademarkList } from "@/api/trademark";
import type { trademarkIlistType } from "@/api/trademark";
import {
  reqBaseSaleList,
  reqSaleImageList,
  reqSaleAttrList,
  reqAddspu,
  reqUpdatespu,
} from "@/api/spu";
import type {
  baseSaleListType,
  saleImageListType,
  saleAttrListType,
  saleAttrItemType,
} from "@/api/spu";

import useCategoryStore from "@/stores/category";
const categoryStore = useCategoryStore();
const { category3Id } = storeToRefs(categoryStore);

//定义一个枚举 代表组件状态
enum compStatus {
  SpuList,
  AddSpu,
  AddSku,
}

// 接受props
const props = defineProps<{
  spuInfo: spuInfoItemType;
}>();
const spuInfo = ref<spuInfoItemType>(cloneDeep(props.spuInfo));
const emit = defineEmits<{
  (event: "changeStatus", status: number): void;
}>();

const cancel = () => {
  emit("changeStatus", compStatus["SpuList"]);
};
/**
 * 初始化数据
 */
const trademarkList = ref<trademarkIlistType>([]);
const baseSaleList = ref<baseSaleListType>([]);
const saleImageList = ref<saleImageListType>([]);
const saleAttrList = ref<saleAttrListType>([]);

const onUseSaleList = computed(() => {
  return baseSaleList.value.filter((item) => {
    return saleAttrList.value.every((item1) => {
      return item1.saleAttrName !== item.name;
    });
  });
});

onMounted(async () => {
  if (props.spuInfo.id) {
    // 有id发4个请求
    const promise1 = reqTrademarkList();
    const promise2 = reqBaseSaleList();
    const promise3 = reqSaleImageList(props.spuInfo.id);
    const promise4 = reqSaleAttrList(props.spuInfo.id);
    try {
      const res = await Promise.all([promise1, promise2, promise3, promise4]);

      trademarkList.value = res[0];
      baseSaleList.value = res[1];
      saleImageList.value = res[2];
      saleAttrList.value = res[3];
      saleImageList.value = saleImageList.value.map((item) => {
        return {
          ...item,
          name: item.imgName,
          url: item.imgUrl,
        };
      });
    } catch (error: any) {
      ElMessage.error("获取初始数据失败" + error.message);
    }
  } else {
    // 没有id发2个请求
    const promise1 = reqTrademarkList();
    const promise2 = reqBaseSaleList();
    try {
      const res = await Promise.all([promise1, promise2]);

      trademarkList.value = res[0];
      baseSaleList.value = res[1];
    } catch (error: any) {
      ElMessage.error("获取初始数据失败" + error.message);
    }
  }
});
const baseUrl = import.meta.env.VITE_API_URL;

// 初始化销售属性值
const baseSaleValue = ref("");

// 添加销售属性
const addSalevalue = () => {
  if (!baseSaleValue.value) return;
  const [baseSaleAttrId, saleAttrName] = baseSaleValue.value.split(":");
  saleAttrList.value.push({
    baseSaleAttrId: +baseSaleAttrId,
    saleAttrName: saleAttrName,
    isEdit: false,
    iptValue: "",
    spuSaleAttrValueList: [],
  });
  baseSaleValue.value = "";
};
// 初始化属性值input框的ref属性
const inpEle = ref();

const goEdit = (row: saleAttrItemType) => {
  row.isEdit = true;
  nextTick(() => {
    inpEle.value.focus();
  });
};
const goLook = (row: saleAttrItemType) => {
  row.isEdit = false;
  // 判断是否为空
  if (!row.iptValue?.trim()) {
    ElMessage.error("添加的属性值不能为空");
    row.iptValue = "";
    return;
  }
  // 判断是否重复
  const isRepetition = row.spuSaleAttrValueList.some((item) => {
    return item.saleAttrValueName === row.iptValue;
  });
  if (isRepetition) {
    ElMessage.error("添加的属性值不能重复");
    row.iptValue = "";
    return;
  }

  row.spuSaleAttrValueList.push({
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: row.iptValue!,
  });
  row.iptValue = "";
};

// 删除某个销售属性值
const deleteAttrValue = (row: saleAttrItemType, index: number) => {
  row.spuSaleAttrValueList.splice(index, 1);
  ElMessage.success("删除成功");
};
// 删除销售属性
const deleteAttr = (index: number) => {
  saleAttrList.value.splice(index, 1);
};

// 保存
const save = async () => {
  // id
  spuInfo.value.category3Id = category3Id.value;
  // 图片列表
  const result = saleImageList.value.map((item) => {
    if (item.id) {
      return {
        imgName: item.imgName,
        imgUrl: item.imgUrl,
      };
    } else {
      return {
        imgName: (item as any).name,
        imgUrl: (item as any).response.data,
      };
    }
  });
  spuInfo.value.spuImageList = result;
  // 属性值列表
  spuInfo.value.spuSaleAttrList = saleAttrList.value;

  try {
    if (spuInfo.value.id) {
      // 修改
      await reqUpdatespu(spuInfo.value);
    } else {
      // 保存
      await reqAddspu(spuInfo.value);
    }
    emit("changeStatus", compStatus["SpuList"]);
    ElMessage.success("保存成功");
  } catch (error: any) {
    ElMessage.error("保存失败:" + error.message);
  }
};
/**
 * 初始化图片墙数据
 */
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
</script>

<style scoped>
.uploadImg {
  width: 100%;
}
</style>
